//
//  GZSQLTableResolver.m
//  GZSQLModelTool_Example
//
//  Created by Guo Rui on 2018/1/25.
//  Copyright © 2018年 GR. All rights reserved.
//

#import "GZSQLTableResolver.h"
#import "GZSQLModelResolver.h"
#import "GZSQLTool.h"
@implementation GZSQLTableResolver

+ (NSArray *)tableSortedColumnNames:(Class)cls uid:(NSString *)uid
{
    // 1. 从隐藏表中获取创建表的sql语句
    NSString *tableName = [GZSQLModelResolver tableName:cls];
    NSString *querySql = [NSString stringWithFormat:@"SELECT sql FROM sqlite_master WHERE type = 'table' and name = '%@'", tableName];
    NSDictionary *dict = [[GZSQLTool executeQuery:querySql uid:uid] firstObject];
    NSString *sql = [dict objectForKey:@"sql"];
    sql = [sql lowercaseString];
    
    // 2. 处理sql字符串，取出所有的columnName
    // CREATE TABLE t_GZStu (score real,number integer,name text, PRIMARY KEY(number))
    NSMutableArray *columnNames = [NSMutableArray array];
    
    sql = [[sql componentsSeparatedByString:@"("] objectAtIndex:1];
    NSArray *compones = [sql componentsSeparatedByString:@","];
    for (NSString *compone in compones) {
        if ([compone containsString:@"primary"]) {
            continue;
        }
        NSString *columnName = [compone componentsSeparatedByString:@" "].firstObject;
        [columnNames addObject:columnName];
    }
    
    // 3. 对取出的columnName数组排序
    return [columnNames sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
}

+ (BOOL)tableIsExist:(Class)cls uid:(NSString *)uid
{
    NSArray *result = [GZSQLTool executeQuery:@"SELECT * FROM sqlite_master" uid:uid];
    return result.count > 0 ? YES : NO;
}

@end
